﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Keepo.Helpers;

namespace AlbumDesigner.Helpers
{
    //this FilterAttribute checks if the current user has permission for the specified section
    public class CheckPermissionAttribute : ActionFilterAttribute
    {
        public string section; //section can be "Albums/Backgrounds/Tips, etc"

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            //get the permissions for this section
            int[] UserPermissionIds = GetPermissionArray(section);

            if (UserPermissionIds.Length > 0)
            {
                if (!UserHelper.HasPermission(UserPermissionIds))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "NoPermission"
                    }));
                }
            }
        }

        private int[] GetPermissionArray(string section)
        {
            int[] UserPermissionIds = new int[0];
            if (section == "Admin")
            {
                UserPermissionIds = UserPermissionHelper.Admin;
            }
            else if (section == "ApprovalChecks")
            {
                UserPermissionIds = UserPermissionHelper.ApprovalChecks;
            }
            else if (section == "BackgroundImages")
            {
                UserPermissionIds = UserPermissionHelper.BackgroundImages;
            }
            else if (section == "FilmingDays")
            {
                UserPermissionIds = UserPermissionHelper.FilmingDays;
            }
            else if (section == "Masks")
            {
                UserPermissionIds = UserPermissionHelper.Masks;
            }
            else if (section == "PageLayouts")
            {
                UserPermissionIds = UserPermissionHelper.PageLayouts;
            }
            else if (section == "PremadePages")
            {
                UserPermissionIds = UserPermissionHelper.PremadePages;
            }
            else if (section == "Tips")
            {
                UserPermissionIds = UserPermissionHelper.Tips;
            }
            else if (section == "Users")
            {
                UserPermissionIds = UserPermissionHelper.Users;
            }
            else if (section == "Albums")
            {
                UserPermissionIds = UserPermissionHelper.Albums;
            }
            else if (section == "DesignVectors")
            {
                UserPermissionIds = UserPermissionHelper.DesignVectors;
            }
            return UserPermissionIds;
        }
    }
}